package com.tom.imooc.staticdatasource;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
public class ProxyHandler implements InvocationHandler {

    private Object target;

    public ProxyHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 默认获取的是接口上面的注解
        DynamicDataSource annotation = method.getAnnotation(DynamicDataSource.class);
        if (annotation == null) {
            //如果接口上没有从方法上获取指定的数据元
            annotation = target.getClass().getDeclaredMethod(method.getName(), method.getParameterTypes()).getAnnotation(DynamicDataSource.class);
        }

        String db = annotation.db();

        Object invoke = null;
        try {
            DataSourceContext.setCurrentDb(db);
            invoke = method.invoke(target, args);
        } finally {
            DataSourceContext.removeCurrentDb();
        }
        return invoke;
    }
}
